package com.renshine.base.util;

import java.util.Enumeration;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 属性静态工具类
 * 
 * @author deyang
 *
 */
public class PropertyUtil {

	private static Logger log = LoggerFactory.getLogger(PropertyUtil.class);
	public static Properties RROP = new Properties();
	
	final public static String STR_JDBC = "jdbc.";
	final public static String STR_JAVA = "java.";
	final public static String STR_ORM = "orm.";
	final public static String STR_HTML = "html.";

	/**
	 * 取得属性文件的对应的值
	 * 
	 * @param key
	 * @return
	 */
	public static String get(String key) {
		if (key != null) {
			Object obj = RROP.get(key);
			if (obj != null) {
				String value = (String) RROP.get(key);
				return value;
			}
		}
		log.info("key={}, 没有配置", key);
		return null;
	}

	/**
	 * 取得以指定属性名开始的所有属性名。<br>
	 * .e.g 如果想获得以client.host开头的属性名<br>
	 * 则可以调用getKeyStartWith("client.host")
	 * 
	 * @param key
	 *            属性名前缀
	 * @return 以指定属性名开头的属性集合
	 */
	public static Set<String> getKeyStartsWith(String key) {
		Set<String> set = new HashSet<String>();
		Enumeration<Object> em = RROP.keys();
		while (em.hasMoreElements()) {
			String name = (String) em.nextElement();
			if (name.startsWith(key)) {
				set.add(name);
			}
		}
		return set;
	}

	/**
	 * 取得数据库信息并保存起来
	 * TODO 这里获取数据库名称，目前暂时且支持mysql
	 * 
	 * @param jdbcUrl 数据库连接URL
	 */
	public static void saveDbName(String jdbcUrl) {
		int begin = jdbcUrl.lastIndexOf("{") + 1;
		int end = jdbcUrl.indexOf("}");
		if (begin == -1 || end == -1) {
			throw new RuntimeException("数据库名称请用{}包含起来");
		}
		String dbName = jdbcUrl.substring(begin, end);
		RROP.setProperty("db.name", dbName);
	}
	
	// 装配其它的类型
	public static void assembleType() {
		Set<String> keys = getKeyStartsWith(STR_JDBC);
		String values[];
		for (String key : keys) {
			values = get(key).split(",");
			if (values.length >= 1) {
				RROP.put(key.replace(STR_JDBC, STR_JAVA), values[0]);				
			}
			if (values.length >= 2) {
				RROP.put(key.replace(STR_JDBC, STR_ORM), values[1]);				
			}
			if (values.length >= 3) {
				RROP.put(key.replace(STR_JDBC, STR_HTML), values[2]);				
			} /*else {
				RROP.put(key.replace(STR_JDBC, STR_HTML), "input");		
			}*/
		}
	}

}
